package com.hly.musicbackground.model.movies.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hly.musicbackground.Utils.JsoupBooksUtil;
import com.hly.musicbackground.Utils.RedisUtil;
import com.hly.musicbackground.dao.MoviesEpisodesDao;
import com.hly.musicbackground.domain.Movies;
import com.hly.musicbackground.domain.MoviesEpisodes;
import com.hly.musicbackground.model.movies.service.MoviesEpisodesService;
import lombok.RequiredArgsConstructor;
import org.jsoup.nodes.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class MoviesEpisodesServiceImpl extends ServiceImpl<MoviesEpisodesDao, MoviesEpisodes> implements MoviesEpisodesService {

    private final RedisUtil redisUtil;
    private final MoviesTencentVideo tencentVideo;

    @Override
    public List<MoviesEpisodes> getMoviesEpisodesList(Movies movies) {

        List<MoviesEpisodes> list = new ArrayList<>();

        if (movies.getType().equals("电影")){
            return list;
        }

        list = lambdaQuery().eq(MoviesEpisodes::getMoviesId, movies.getMoviesId())
                .list();

        if (list.size() > 0){
            return list;
        }

        String lockKey = "music:movies:getMoviesEpisodesList:" + movies.getMoviesId();

        boolean b = redisUtil.tryLock(lockKey);

        try {
            if (!b){
                Thread.sleep(200);
                return getMoviesEpisodesList(movies);
            }

            while (true){
                Document allDoc = JsoupBooksUtil.getAllDoc(movies.getUrl(), "v.qq.com");
                list = tencentVideo.getMoviesEpisodes(allDoc, movies);
                if (list.size() > 0){
                    break;
                }
            }

            saveBatch(list);

        }catch (Exception e){
            e.printStackTrace();
        }
        finally {
            redisUtil.releaseLock(lockKey);
        }


        return list;
    }
}
